const router=require('koa-router')();
const koaBody=require('koa-body');
const events=require('events');
const moment=require('moment');
const {User,Post,Archive}=require('../models/index');
const redis=require('../models/redis.server.model');
const config=require('../config/config');
const checkLogin=require('../middlewares/checkLogin');
const timeLimit=require('../middlewares/timeLimit');
const verifyPost=require('../lib/verifyPost');

//话题发表页面
router.get('/',checkLogin(),async ctx=>{
    await ctx.render('post',{
        title:'发表',
        postTags:config.post.tags,
        loginUser:ctx.session.loginUser,
        success:ctx.flash.success,
        error:ctx.flash.error,
        postCharacterLengthLimit:config.characterLengthLimit.post
    });
});

//发表话题
router.post('/',checkLogin(),timeLimit({action:'post'}),koaBody(), async ctx=>{
    let {body}=ctx.request,ee=new events();
    ee.on('invalid',msg=>{
       ctx.flash={error:msg};
       ctx.redirect('back');
    });

    let verifyPostRet=verifyPost(body);

    if(verifyPostRet)return ee.emit('invalid',verifyPostRet);
    let user=await User.findOne({_id:ctx.session.loginUser._id});
    if(!user)return ee.emit('invalid','用户不存在');

    let time=new Date(),archive=moment(time).format('YYYY-MM');

    await Promise.all([
        new Post({
            title:body.title,
            tags:body.tags,
            intro:body.intro,
            content:body.content,
            author:ctx.session.loginUser,
            time,
            archive
        }).save(),
        User.update({_id:user._id},{$inc:{score:config.score.post}}),
        Archive.update({archive},{$inc:{count:1}},{upsert:true}),
        redis.addLimit({action:'post',id:ctx.session.loginUser._id})
    ]);
    ctx.session.loginUser.score+=config.score.post;
    ctx.flash={success:'发表成功'};
    ctx.redirect('back');
});

module.exports=router;